clc; close all
% create heatmap
load('c2test-bboxes.mat')
heatmap_all = {};
% fp = fopen('c4prop.txt', 'r');
imid = 1;
while 1
    if imid > length(bboxes)
        break
    end
    %% prepare
    imname = ['img_', num2str(imid), '.jpg'];
    im = imread(['c2-test-color/', imname]) * 1;
    [imh, imw, ~] = size(im);
    bbox = bboxes{imid};
    bbox = bbox(2 : end, :);
    %% build heatmap
    heatmap = 0 * ones(round(imh / 4), round(imw / 4));
    for bid = 1 : size(bbox, 1)
        for hh = bbox(bid, 7) :  min(bbox(bid, 7) + floor(1 / bbox(bid, 8)), size(heatmap, 1))
            for ww = bbox(bid, 6) : min(bbox(bid, 6) + floor(1 / bbox(bid, 8)), size(heatmap, 2))
                if heatmap(hh, ww) < bbox(bid, 1)
                    heatmap(hh, ww) = bbox(bid, 1);
                end
            end
        end
    end
    imid = imid + 1;
    heatmap_all = [heatmap_all, {heatmap}];
end
clc; close all
ratios = load('tst-ratios.txt');
% load('c2test-bboxes-coding2-asymmetric.mat')
load('c2test-bboxes-coding2.mat')
% fp = fopen('c2prop-large.txt', 'r');
imid = 1;
while 1
    if imid > length(bboxes)
        break
    end
%     if imid > 10
%         imid = imid + 1;
%         continue
%     end
%     imname = fgetl(fp);
%     if imname == -1
%         break
%     end
%     strs = regexp(imname, ' ', 'split');
%     imname = strs{1};
    heatmap = heatmap_all{imid};
    imname = ['img_', num2str(imid), '.jpg'];
    im = imread(['c2-test-color/', imname]) * 1;
    ori_im = imread(['c2-test-color-ori/', imname]);
    [imh, imw, ~] = size(im);
    [ori_imh, ori_imw, ~] = size(ori_im);
    if size(im, 3) == 1
        im = repmat(im, [1, 1, 3]);
    end
    bbox = bboxes{imid};
    bbox = bbox(2 : end, :);
    bbox = bbox(bbox(:, 1) > 0.5, :);
    % remove cutted boxes
    remove_id = [];
    for bid = 1 : size(bbox, 1)
        scale = bbox(bid, 12);
        left_offset = bbox(bid, 13);
        top_offset = bbox(bid, 14);
        right_offset = left_offset + 319;
        bottom_offset = top_offset + 319;
        
        left_offset = left_offset / scale;
        top_offset = top_offset / scale;
        right_offset = right_offset / scale;
        bottom_offset = bottom_offset / scale;
        
        x_range = bbox(bid, 2 : 2 : 9);
        y_range = bbox(bid, 3 : 2 : 9);
        
        if min(x_range) < left_offset || max(x_range) > right_offset || ...
                min(y_range) < top_offset || max(y_range) > bottom_offset
            remove_id = [remove_id, bid];
        end
    end
    bbox(remove_id, :) = [];
    
% remove by heatmap
%     remove_id = [];
%     for bid = 1 : size(bbox, 1)
%         centerx_label = bbox(bid, 10);
%         centery_label = bbox(bid, 11);
%         if heatmap(centery_label, centerx_label) < 0.7
%             remove_id = [remove_id, bid];
%         end
%     end
%     bbox(remove_id, :) = [];
    
    bbox = bbox(:, 1 : 9);
    tic
%     pick = nms_textline_8p(bbox, 0.5);
%     bbox = bbox(pick, :);
%     bbox = nms_textline_8p_v3(bbox, 0.5);

    bbox = nmsfuse_textline_8p(bbox, 0.5);

    toc
    
    bbox = ceil(bbox(:, 2 : 9));
    
    
    bbox(:, 1 : 2 : 8) = min(max(bbox(:, 1 : 2 : 8), 1), imw - 1);
    bbox(:, 2 : 2 : 8) = min(max(bbox(:, 2 : 2 : 8), 1), imh - 1);
    
    % remove duplicate
    remove_id = [];
    for bid1 = 1 : size(bbox, 1) - 1
        for bid2 = bid1 + 1 : size(bbox, 1)
            if sum(bbox(bid1, :) - bbox(bid2, :)) == 0
                remove_id = [remove_id, bid2];
            end
        end
    end
    bbox(remove_id, :) = [];
    
    % remove verticle line
    remove_id = [];
    edge_len = zeros(size(bbox, 1), 4);
    for bid = 1 : size(bbox, 1)
        for lid = 1 : 3
            edge_len(bid, lid) = dis(bbox(bid, 2 * lid - 1 : 2 * lid), bbox(bid, 2 * lid + 1 : 2 * lid + 2));
        end
        edge_len(bid, 4) = dis(bbox(bid, 7 : 8), bbox(bid, 1 : 2));
        if mean([edge_len(bid, 2), edge_len(bid, 4)]) / mean([edge_len(bid, 1), edge_len(bid, 3)]) > 3
            remove_id = [remove_id, bid];
        end
    end
    bbox(remove_id, :) = [];
    edge_len(remove_id, :) = [];
    
    % fuse verticle overlapped
    bbox = [bbox, zeros(size(bbox, 1), 1)];
    for bid1 = 1 : size(bbox, 1) - 1
        if bbox(bid1, end) == 0
            bbox(bid1, end) = max(bbox(:, end)) + 1;
        end
        for bid2 = bid1 + 1 : size(bbox, 1)
            % verticle overlap > 0.5
            union_top = max([bbox(bid1, [2, 4]), bbox(bid2, [2, 4])]);
            union_bottom = min([bbox(bid1, [6, 8]), bbox(bid2, [6, 8])]);
            union_verticle = max(union_bottom - union_top + 1, 0);
            verticle_overlap_ratio = union_verticle / min([edge_len(bid1, [2 4]), edge_len(bid2, [2 4])]);
            if verticle_overlap_ratio < 0.5
                continue
            end
            % horizon overlap > 0 or  ... some too specific tricks
            union_left = max([bbox(bid1, [1, 7]), bbox(bid2, [1, 7])]);
            union_right = min([bbox(bid1, [3, 5]), bbox(bid2, [3, 5])]);
            merge = false;
            if union_right - union_left < 0 && union_right - union_left > -0.2 * union_verticle && max([edge_len(bid1, [2 4]), edge_len(bid2, [2 4])]) > 50
                merge = true;
            elseif union_right - union_left > 0
                merge = true;
            end
            if merge
                if bbox(bid2, end) == 0
                    bbox(bid2, end) = bbox(bid1, end);
                else
                    bbox(bbox(:, end) == bbox(bid2, end), end) = bbox(bid1, end);
                end
            end
        end
    end
    % group boxes into line
    line_id_all = unique(bbox(:, end));
    line_boxes = zeros(length(line_id_all), 4);
    for lid = 1 : size(line_boxes, 1)
        line_id = line_id_all(lid);
        tmp_box = bbox(bbox(:, end) == line_id, 1 : 8);
        line_box = zeros(1, 8);
        line_box(1) = min(tmp_box(:, 1));
        line_box(2) = max(tmp_box(:, 2));
        line_box(3) = max(tmp_box(:, 3));
        line_box(4) = min(tmp_box(:, 4));
        line_box(5) = max(tmp_box(:, 5));
        line_box(6) = min(tmp_box(:, 6));
        line_box(7) = min(tmp_box(:, 7));
        line_box(8) = max(tmp_box(:, 8));
        line_boxes(lid, :) = [mean(line_box([1 7])), min(line_box([2 4])), mean(line_box([3 5])), max(line_box([6 8]))];
    end
    
    line_boxes = round(line_boxes * ratios(imid));
    line_boxes(:, [1 3]) = max(min(line_boxes(:, [1 3]), ori_imw - 1), 0);
    line_boxes(:, [2 4]) = max(min(line_boxes(:, [2 4]), ori_imh - 1), 0);
    
    fpre = fopen(['res_img_', num2str(imid), '.txt'], 'w'); %, 'n', 'utf-8');
    for lid = 1 : size(line_boxes, 1)
        for cid = 1 : 3
            fprintf(fpre, '%d, ', line_boxes(lid, cid));
        end
        fprintf(fpre, '%d\r\n', line_boxes(lid, 4));
        ori_im = bitmapplot(line_boxes(lid, [2 2 4 4 2]), line_boxes(lid, [1 3 3 1 1]), ori_im, struct('LineWidth', 2, 'Color', [0 1 0 1]));
    end
    fclose(fpre);

%     figure
%     imshow(im)
    imwrite(ori_im, [imname, '-gt.png'], 'png');
    imid = imid + 1;
%     break
end

% fclose(fp);



